package com.currency.mall.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.currency.mall.Constant;
import com.currency.mall.R;
import com.currency.mall.di.component.DaggerRegisterComponent;
import com.currency.mall.di.modlue.RegisterModule;
import com.currency.mall.util.PwdCheckUtil;
import com.currency.mall.widget.VerifyCodeView;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.commonbase.util.ToastUitl;

import java.text.SimpleDateFormat;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/12/11.
 */

public class RegisterActivity extends BaseActivity<RegisterPresent> implements RegisterContract.View {


    @BindView(R.id.btn_next_step)
    Button btnNextStep;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.et_input_pwd)
    EditText etInputPwd;
    @BindView(R.id.rl_pwd)
    RelativeLayout rlPwd;
    @BindView(R.id.et_confirm_pwd)
    EditText etConfirmPwd;
    @BindView(R.id.rl_et_confirm_pwd)
    RelativeLayout rlEtConfirmPwd;
    @BindView(R.id.ll_set_pwd)
    LinearLayout llSetPwd;
    @BindView(R.id.iv_pwd)
    ImageView ivPwd;
    @BindView(R.id.iv_confirm_pwd)
    ImageView ivConfirmPwd;
    @BindView(R.id.verifyCodeView)
    VerifyCodeView verifyCodeView;
    @BindView(R.id.et_verifyCode)
    EditText etVerifyCode;
    @BindView(R.id.rl_verification_code)
    RelativeLayout rlVerificationCode;
    @BindView(R.id.et_phone_verifyCode)
    EditText etPhoneVerifyCode;
    @BindView(R.id.tv_send_code)
    TextView tvSendCode;
    @BindView(R.id.et_proxy_code)
    EditText etProxyCode;
    @BindView(R.id.et_input_phone)
    EditText etInputPhone;
    @BindView(R.id.rl_phone)
    RelativeLayout rlPhone;
    @BindView(R.id.rl_proxy_code)
    RelativeLayout rlProxyCode;
    private boolean pwdDisplayFlg = false;
    private boolean confirmPwdDisplayFlg = false;
    private MyTime myTime;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.title_color));
        StatusBarUtils.StatusBarLightMode(this);
        init();
    }

    @Override
    public void initInjector() {
        DaggerRegisterComponent.builder()
                .registerModule(new RegisterModule(this))
                .build()
                .inject(this);
    }

    private void init() {
        myTime = new MyTime(60000, 1000);
        btnNextStep.getBackground().setAlpha(50);
        btnNextStep.setClickable(false);
        etInputPhone.addTextChangedListener(phoneTextWatcher);
        etPhoneVerifyCode.addTextChangedListener(textWatcher);
        etVerifyCode.addTextChangedListener(textWatcher);
        etInputPwd.addTextChangedListener(textWatcher);
        etConfirmPwd.addTextChangedListener(textWatcher);
        etProxyCode.addTextChangedListener(textWatcher);
        verifyCodeView.loadUrl(Constant.IMAGECODE);
        verifyCodeView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                verifyCodeView.reload();
                return false;
            }
        });
    }


    TextWatcher phoneTextWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String strInputPhone = etInputPhone.getText().toString().trim();
            String strPhoneVerifyCode = etPhoneVerifyCode.getText().toString().trim();
            String strInputPwd = etInputPwd.getText().toString().trim();
            String strConfirmPwd = etConfirmPwd.getText().toString().trim();
            String strProxyCode = etProxyCode.getText().toString().trim();
            String strVerifyCode = etVerifyCode.getText().toString().trim();
            if (TextUtils.isEmpty(strInputPhone) || TextUtils.isEmpty(strPhoneVerifyCode) ||TextUtils.isEmpty(strInputPwd) ||TextUtils.isEmpty(strConfirmPwd) ||TextUtils.isEmpty(strProxyCode) ||TextUtils.isEmpty(strVerifyCode) ||TextUtils.isEmpty(s)) {
                btnNextStep.setBackgroundResource(R.drawable.btn_bg);
                btnNextStep.getBackground().setAlpha(50);
                btnNextStep.setClickable(false);
            } else {
                btnNextStep.setBackgroundResource(R.drawable.btn_bg);
                btnNextStep.getBackground().setAlpha(250);
                btnNextStep.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (TextUtils.isEmpty(s.toString())) {
                rlPhone.setVisibility(View.INVISIBLE);
            } else {
                rlPhone.setVisibility(View.VISIBLE);
            }
        }
    };

    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            String strInputPhone = etInputPhone.getText().toString().trim();
            String strPhoneVerifyCode = etPhoneVerifyCode.getText().toString().trim();
            String strInputPwd = etInputPwd.getText().toString().trim();
            String strConfirmPwd = etConfirmPwd.getText().toString().trim();
            String strProxyCode = etProxyCode.getText().toString().trim();
            String strVerifyCode = etVerifyCode.getText().toString().trim();
            if (TextUtils.isEmpty(strInputPhone) || TextUtils.isEmpty(strPhoneVerifyCode) ||TextUtils.isEmpty(strInputPwd) ||TextUtils.isEmpty(strConfirmPwd) ||TextUtils.isEmpty(strProxyCode) ||TextUtils.isEmpty(strVerifyCode) ||TextUtils.isEmpty(s)) {
                btnNextStep.setBackgroundResource(R.drawable.btn_bg);
                btnNextStep.getBackground().setAlpha(50);
                btnNextStep.setClickable(false);
            } else {
                btnNextStep.setBackgroundResource(R.drawable.btn_bg);
                btnNextStep.getBackground().setAlpha(250);
                btnNextStep.setClickable(true);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    private void pwdTransformation() {

        if (!pwdDisplayFlg) {
            // display password text, for example "123456"
            etInputPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            etInputPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        pwdDisplayFlg = !pwdDisplayFlg;

        etInputPwd.postInvalidate();

        if (pwdDisplayFlg) {
            ivPwd.setImageResource(R.drawable.yanjing_xianshi);
        } else {
            ivPwd.setImageResource(R.drawable.yanjing_guanbi);
        }
        etInputPwd.setSelection(etInputPwd.getText().toString().length());
    }

    private void confirmPwdTransformation() {

        if (!confirmPwdDisplayFlg) {
            // display password text, for example "123456"
            etConfirmPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            etConfirmPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        confirmPwdDisplayFlg = !confirmPwdDisplayFlg;

        etConfirmPwd.postInvalidate();

        if (confirmPwdDisplayFlg) {
            ivConfirmPwd.setImageResource(R.drawable.yanjing_xianshi);
        } else {
            ivConfirmPwd.setImageResource(R.drawable.yanjing_guanbi);
        }
        etConfirmPwd.setSelection(etConfirmPwd.getText().toString().length());
    }


    class MyTime extends CountDownTimer {

        public MyTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Date date = new Date(millisUntilFinished);
            SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
            String str = sdf.format(date);
            tvSendCode.setText("验证码"+"(" + millisUntilFinished / 1000+"s"+ ")");
        }

        @Override
        public void onFinish() {
            tvSendCode.setText("获取验证码");
        }
    }


    @OnClick({R.id.ll_back, R.id.btn_next_step, R.id.iv_confirm_pwd, R.id.iv_pwd,R.id.tv_send_code,R.id.rl_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.iv_pwd:
                pwdTransformation();
                break;
            case R.id.iv_confirm_pwd:
                confirmPwdTransformation();
                break;
            case R.id.rl_phone:
                etInputPhone.setText("");
                rlPhone.setVisibility(View.GONE);
                break;
            case R.id.btn_next_step:
                if (etVerification()) {
                    mPresenter.checkCode();
                }
                break;
            case R.id.tv_send_code:
                if(sendCodeVerification()){
                    mPresenter.sendCode("REG");
                }
                break;

        }
    }

    @Override
    public String getPhone() {
        return etInputPhone.getText().toString().trim();
    }

    @Override
    public String getPhoneVerifyCode() {
        return etPhoneVerifyCode.getText().toString().trim();
    }


    @Override
    public String getpwd() {
        return etInputPwd.getText().toString().trim();
    }

    @Override
    public String getConfirmpwd() {
        return etConfirmPwd.getText().toString().trim();
    }

    @Override
    public String getProxyCode() {
        return etProxyCode.getText().toString().trim();
    }

    @Override
    public String getVerifyCode() {
        return etVerifyCode.getText().toString().trim();
    }

    @Override
    public void sendCodesuccess() {
        myTime.start();
    }

    @Override
    public void checkCodesuccess() {
        mPresenter.register();
    }

    private boolean etVerification() {
        String setInputPhone = etInputPhone.getText().toString().trim();
        String strPhoneVerifyCode = etPhoneVerifyCode.getText().toString().trim();
        String strProxyCode = etProxyCode.getText().toString().trim();
        String strVerifyCode = etVerifyCode.getText().toString().trim();
        String strPwd = etInputPwd.getText().toString();
        String strConfirmPwd = etConfirmPwd.getText().toString();
        if(setInputPhone.length()<10){
            ToastUitl.show("请输入正确的手机", 200);
            return false;
        }else if (strPwd.length() < 8) {
            ToastUitl.show("密码长度是8到32位", 200);
            return false;
        } else if (strConfirmPwd.length() < 8) {
            ToastUitl.show("密码长度是8到32位", 200);
            return false;
        } else if (!strPwd.equals(strConfirmPwd)) {
            ToastUitl.show("两次输入的密码不一致", 200);
            return false;
        } else if (!PwdCheckUtil.isPasswordInfo(strPwd)) {
            ToastUitl.show("密码须包含数字、字母、符号至少2种或以上元素", 200);
            return false;
        } else if (!PwdCheckUtil.isPasswordInfo(strConfirmPwd)) {
            ToastUitl.show("密码须包含数字、字母、符号至少2种或以上元素", 200);
            return false;
        }
        return true;

    }

    private boolean sendCodeVerification() {
        String setInputPhone = etInputPhone.getText().toString().trim();
        String strPhoneVerifyCode = etPhoneVerifyCode.getText().toString().trim();
        if("".equals(setInputPhone)){
            ToastUitl.show("请输入手机号码", 200);
            return false;
        }else if (setInputPhone.length()<10) {
            ToastUitl.show("请输入正确的手机", 200);
            return false;
        }else if ("".equals(strPhoneVerifyCode)) {
            ToastUitl.show("请输入图形验证码", 200);
            return false;
        }
        return true;
    }


    @Override
    public void toLogin() {
        startActivity(new Intent(getContext(), LoginActivity.class));
        finish();
    }

    @Override
    public void phoneVerifyCodeFail() {
        verifyCodeView.loadUrl(Constant.IMAGECODE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (myTime != null) {
            myTime.cancel();
        }
    }

}
